#!/user/bin/env python3
# -*- coding: utf-8 -*-
import json

# 定义打印输出函数，用来展示数据使用
def printpy(outdata):
    if outdata.ErrorCode!=0:
        print('error code:'+str(outdata.ErrorCode)+'\n')
        return()
    for i in range(0,len(outdata.Data[0])):
        strTemp=''
        if len(outdata.Times)>1:
            strTemp=str(outdata.Times[i])+' '
        for k in range(0, len(outdata.Fields)):
            strTemp=strTemp+str(outdata.Data[k][i])+' '
        print(strTemp)

def check_api_error(func):
    """
    A decorator for WindPy functions, so that if a function fails to retrieve data, it will print the error code and the relevant message before exiting
    :param func: WindPy function that returns a WindData object
    :return: wrapper
    """

    def wrapper(*args, **kwargs):
        data = func(*args, **kwargs)
        if data.ErrorCode != 0:
            print(data)
            exit()
        return data
    return wrapper

# 将wind的数据保存为json
def saveToJson(wind_data, file_name):
    with open(file_name+'.json', mode='w') as f:
        json.dump(wind_data.Data[0], f)
    print(file_name+" JSON文件已被保存")

def saveToCsv(wind_df, file_name):
    if not wind_df.empty:
        wind_df.to_csv(file_name+'.csv', encoding='utf_8_sig')
        print(file_name+" CSV文件已被保存")
    else:
        print('该dataframe为空，没有文件被保存。')
